<template>
    <a-tree
        :checkable="checkable" 
        :treeData="treeData"
        :replaceFields="replaceFields"
        :checkedKeys="checkedKeys"
        :expandedKeys="expandedKeys"
        :checkStrictly="checkStrictly"
        :autoExpandParent="autoExpandParent"
        @check="onCheck"
        @select="onSelect"
        @expand="onExpand">
    </a-tree>
</template>

<script>
export default {
    name:'LTree',
    props:{
        checkable:{
            type:Boolean,
            default:false
        },
        treeData:{
            type:Array,
            default:()=>[]
        },
        replaceFields:{
            type:Object,
            default:()=>{}
        },
        checkStrictly:{
            type:Boolean,
            default:false
        },
        autoExpandParent:{
            type:Boolean,
            default:true
        }

    },
    data(){
        return{
            checkedKeys:[],//选中的节点
            halfCheckedKeys:[],//半选中的节点
            expandedKeys:[],//展开的节点
            allKeys:[],//树中所有的节点信息
        }
    },
    created(){
        

    },
    mounted(){
       
    },
    watch:{
        treeData(){
           this.getAllKeys();
        }
    },
    methods:{
        onCheck(checkedKeys,e){
            if(this.checkStrictly){
                this.checkedKeys = checkedKeys.checked;
            }else{
                this.checkedKeys = checkedKeys
                this.halfCheckedKeys=e.halfCheckedKeys
            }
            let checked={checkedKeys:this.checkedKeys,halfCheckedKeys:this.halfCheckedKeys}
            this.$emit("onCheck",checked)
        },
        onExpand(expandedKeys,e){
             this.expandedKeys = expandedKeys;
        },
        onSelect(selectedKeys,e){
             let vNode ={key:e.node.eventKey,title:e.node.title,value:e.node.value || ''}
             this.$emit("onSelect",vNode)
        },
        //取消所有
        cancelCheckALL(){
            this.checkedKeys=[]
        },
         //选中所有
        checkALL () {
            this.checkedKeys = this.allKeys;
        },
        //展开所有
        expandAll(){
            this.expandedKeys = this.allKeys;
        },
        //关闭所有
        closeAll(){
            this.expandedKeys = [];
        },
        getAllKeys(){
            let that = this
            that.allKeys=[];
            
            if(that.treeData){
                let localReplaceFields = that.replaceFields
                if(!localReplaceFields){
                    localReplaceFields={};
                }
                let isReplace = JSON.stringify(localReplaceFields) == "{}";
                that.treeData.forEach(function(val, index){
                    that.allKeys.push(isReplace?val["key"]:val[localReplaceFields["key"]])
                });

                //如果默认展开，则展开所有节点
                if(that.autoExpandParent){
                    that.expandAll();
                }
            }
        }

    }
}
</script>